package com.isunland.managesystem.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.SimpleConfirmDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.RetrievePasswordParams;
import com.isunland.managesystem.entity.SimpleDialogParams;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.SMSContentObserver;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONException;

/**
 * 对象功能: 找回密码
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/5/2 10:44
 */
public class RetrievePasswordFragment extends BaseFragment implements View.OnClickListener {
  public static final String EXTRA_USERNAME =
      RetrievePasswordFragment.class.getSimpleName() + ".EXTRA_USERNAME";
  public static final String EXTRA_PASSWORD =
      RetrievePasswordFragment.class.getSimpleName() + ".EXTRA_PASSWORD";
  @BindView(R.id.username) EditText mEtUsername;
  @BindView(R.id.et_phone) EditText mEtPhone;
  @BindView(R.id.et_testCode) EditText mEtTestCode;
  @BindView(R.id.tv_testCode) TextView mTvSendTestCode;
  @BindView(R.id.btn_resetPassword) Button mBtnResetPassword;
  //倒计时
  CountDownTimer timer = new CountDownTimer(59000, 1000) {
    @Override public void onTick(long time) {
      mTvSendTestCode.setText(String.format(Locale.CHINA, "%d秒后重发", time / 1000));
      mTvSendTestCode.setEnabled(false);
    }

    @Override public void onFinish() {
      resetTestCode();
    }
  };
  @SuppressLint("HandlerLeak") Handler mHandler = new Handler() {
    @Override public void handleMessage(Message msg) {
      LogUtil.i("msg=" + msg.obj);
      if (msg.what == 1 && null != msg.obj) {
        mEtTestCode.setText(msg.obj.toString());
      }
    }
  };
  private RetrievePasswordParams mParams;

  private void resetTestCode() {
    mTvSendTestCode.setText("获取验证码");
    mTvSendTestCode.setEnabled(true);
  }

  @Override public void initData() {
    super.initData();
    mParams = mBaseParams instanceof RetrievePasswordParams ? (RetrievePasswordParams) mBaseParams
        : new RetrievePasswordParams();
  }

  @Override protected int initLayoutId() {
    return R.layout.fragment_retrieve_password;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    setTitleCustom(R.string.resetPassword);
    mEtUsername.setText(mParams.getAccout());
    //从后台获取绑定数据,而不是本机号码.
    //mEtPhone.setText(MyUtils.getPhoneNumber(mActivity));

    mTvSendTestCode.setOnClickListener(this);
    mBtnResetPassword.setOnClickListener(this);

    mActivity.getContentResolver()
        .registerContentObserver(Uri.parse("content://sms/"), true,
            new SMSContentObserver(mActivity, mHandler));
    volleyPostGetPhone();
  }

  private void volleyPostGetPhone() {
    if (MyStringUtil.isEmptyTextView(mEtUsername)) return;
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_QUERY_RELATED_PHONE_V286);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("username", MyStringUtil.getText(mEtUsername));
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        Base result = new Gson().fromJson(arg0, Base.class);
        if (Base.SUCCESS == result.getResult()) {
          mEtPhone.setText(result.getMessage());
        }
      }
    });
  }

  @Override public void onClick(View view) {
    if (view == null) return;
    switch (view.getId()) {
      case R.id.tv_testCode:
        volleyPostCode();
        break;

      case R.id.btn_resetPassword:
        volleyPostResetPassword();
        break;
    }
  }

  private void volleyPostResetPassword() {
    if (MyStringUtil.isEmptyTextView(mEtPhone)
        || MyStringUtil.isEmptyTextView(mEtUsername)
        || MyStringUtil.isEmptyTextView(mEtTestCode)) {
      ToastUtil.show(R.string.notComplete);
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RESET_PASSWORD_V286);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("username", MyStringUtil.getText(mEtUsername));
    params.put("phoneNumber", MyStringUtil.getText(mEtPhone));
    params.put("identifyingCode", MyStringUtil.getText(mEtTestCode));
    MyUtils.showDialogLoading(mActivity, R.string.loading1);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        Base result = new Gson().fromJson(arg0, Base.class);
        if (Base.SUCCESS == result.getResult()) {
          //设定回传信息
          Intent intent = new Intent();
          intent.putExtra(EXTRA_USERNAME, MyStringUtil.getText(mEtUsername));
          intent.putExtra(EXTRA_PASSWORD, "123456");
          mActivity.setResult(Activity.RESULT_OK, intent);
        }
        //显示对话框
        SimpleDialogParams params = new SimpleDialogParams();
        params.setMessage(result.getMessage());
        params.setFinishActivityOnDismiss(result.getResult() == 1);
        showDialog(SimpleConfirmDialogFragment.newInstance(params), 0);
      }
    });
  }

  /** 获取验证码 */
  private void volleyPostCode() {
    if (MyStringUtil.isEmptyTextView(mEtPhone)) {
      ToastUtil.show(MyStringUtil.connect(R.string.mobile, R.string.notEmpty));
      return;
    }
    if (MyStringUtil.isEmptyTextView(mEtUsername)) {
      ToastUtil.show(MyStringUtil.connect(R.string.userName, R.string.notEmpty));
      return;
    }
    //发送成功后,60秒内不可点击,防止频繁发送.
    timer.start();
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TEST_CODE_V286);
    HashMap<String, String> params = new HashMap<>();
    params.put("phoneNumber", MyStringUtil.getText(mEtPhone));
    params.put("username", MyStringUtil.getText(mEtUsername));
    params.put("isERP", MyStringUtil.valueOf(!MyUtils.isWeiJia()));
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
        finishTimer();
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        Base result = new Gson().fromJson(arg0, Base.class);
        ToastUtil.show(result.getMessage());
        if (Base.FAILURE == result.getResult()) {
          finishTimer();
        }
      }
    });
  }

  private void finishTimer() {
    timer.cancel();
    resetTestCode();
  }
}
